package org.jeecg.modules.system.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysArea;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.qo.SysDeleteQO;
import org.jeecg.modules.system.service.ISysAreaService;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 区划管理
 * @Author: jeecg-boot
 * @Date:   2020-09-22
 * @Version: V1.0
 */
@Slf4j
@Api(tags="区划管理")
@RestController
@RequestMapping("/system/sysArea")
public class SysAreaController extends JeecgController<SysArea, ISysAreaService> {
	@Autowired
	private ISysAreaService sysAreaService;
	
	/**
	  * 根据区划名查询列表
	  *
	  * @param questionType
	  * @param req
	  * @return
	  */
	 @ApiOperation(value="区划管理-根据区划名查询列表", notes="区划管理-根据区划名查询列表")
	 @GetMapping(value = "/questionTypeList")
	 public Result<?> queryList(SysArea sysArea, HttpServletRequest req) {
		 QueryWrapper<SysArea> queryWrapper = new QueryWrapper<SysArea>();
		 if(oConvertUtils.isNotEmpty(sysArea.getAreaName())) {
			 queryWrapper.like("area_name", sysArea.getAreaName());
		 }
		 queryWrapper.eq("del_flag", 0);
		 List<SysArea> list = sysAreaService.list(queryWrapper);
		 return Result.ok(list);
	 }
	
	/**
	 * 分页列表查询
	 *
	 * @param sysArea
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="区划管理-分页列表查询", notes="区划管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(SysArea sysArea,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<SysArea> queryWrapper = QueryGenerator.initQueryWrapper(sysArea, req.getParameterMap());
		Page<SysArea> page = new Page<SysArea>(pageNo, pageSize);
		IPage<SysArea> pageList = sysAreaService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 * 添加
	 *
	 * @param sysArea
	 * @return
	 */
	@AutoLog(value = "区划管理-添加")
	@ApiOperation(value="区划管理-添加", notes="区划管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SysArea sysArea) {
		LambdaQueryWrapper<SysArea> queryWrapper = new LambdaQueryWrapper<SysArea>();
		queryWrapper.eq(SysArea::getAreaCode, sysArea.getAreaCode());
		queryWrapper.eq(SysArea::getDelFlag, CommonConstant.DEL_FLAG_0);
		int num = sysAreaService.count(queryWrapper);
		if(num>0) {
			return Result.error("区划编码重复！");
		}
		sysAreaService.save(sysArea);
		return Result.ok("添加成功！");
	}
	
	/**
	 * 编辑
	 *
	 * @param sysArea
	 * @return
	 */
	@AutoLog(value = "区划管理-编辑")
	@ApiOperation(value="区划管理-编辑", notes="区划管理-编辑")
	@PostMapping(value = "/edit")
	public Result<?> edit(@RequestBody SysArea sysArea) {
		sysAreaService.updateById(sysArea);
		return Result.ok("编辑成功!");
	}
	
	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "区划管理-通过id删除")
	@ApiOperation(value="区划管理-通过id删除", notes="区划管理-通过id删除")
	@PostMapping(value = "/delete")
	public Result<?> delete(@RequestBody SysDeleteQO data) {
		SysArea sysArea = sysAreaService.getById(data.getId());
		if(sysArea==null) {
			return Result.error("数据不存在");
		}
		QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>(new SysArea());
        queryWrapper.and(wrapper -> wrapper.eq("del_flag", CommonConstant.DEL_FLAG_0));
        queryWrapper.and(wrapper -> wrapper.eq("parent_id", data.getId()));
        List<SysArea> delData = new ArrayList<SysArea>();
        List<SysArea> childrenList = sysAreaService.list(queryWrapper);
        if (childrenList != null && childrenList.size() > 0) {
        	for(int j=0;j<childrenList.size();j++) {
        		SysArea children = childrenList.get(j);
        		children.setDelFlag(CommonConstant.DEL_FLAG_1);
        		delData.add(children);
        	}
//            return Result.error("该区划存在下级，无法删除");
        }
		sysArea.setDelFlag(CommonConstant.DEL_FLAG_1);
		delData.add(sysArea);
		sysAreaService.updateBatchById(delData);
		return Result.ok("删除成功!");
	}
	
	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "区划管理-批量删除")
	@ApiOperation(value="区划管理-批量删除", notes="区划管理-批量删除")
	@PostMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestBody SysDeleteQO data) {
		if (data==null || data.getIds() == null || "".equals(data.getIds().trim())) {
			return Result.error("参数不识别！");
		}
        String[] ids = data.getIds().split(",");
		List<SysArea> list = new ArrayList<SysArea>();
		for(int i=0; i<ids.length; i++) {
			if(oConvertUtils.isNotEmpty(ids[i])) {
				SysArea sysArea = sysAreaService.getById(ids[i]);
				if(sysArea==null) {
					return Result.error("数据不存在");
				}
				sysArea.setDelFlag(CommonConstant.DEL_FLAG_1);
				list.add(sysArea);
				
				//删除子节点
				QueryWrapper<SysArea> queryWrapperChild = new QueryWrapper<>(new SysArea());
		        queryWrapperChild.and(wrapper -> wrapper.eq("del_flag", CommonConstant.DEL_FLAG_0));
		        queryWrapperChild.in("parent_id", ids[i]);
		        List<SysArea> childrenList = sysAreaService.list(queryWrapperChild);
		        if (childrenList != null && childrenList.size() > 0) {
		        	for(int j=0;j<childrenList.size();j++) {
		        		SysArea children = childrenList.get(j);
		        		children.setDelFlag(CommonConstant.DEL_FLAG_1);
		        		list.add(children);
		        	}
//		            return Result.error("所选区划存在下级，无法删除");
		        }
			}
		}
		sysAreaService.updateBatchById(list);
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="区划管理-通过id查询", notes="区划管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SysArea sysArea = sysAreaService.getById(id);
		return Result.ok(sysArea);
	}
	
	/**
	 * 获取树状列表
	 *
	 * @param ParentId
	 * @return
	 */
	@ApiOperation(value="区划管理-获取树状列表", notes="区划管理-通过ParentId查询下级小类")
	@GetMapping(value = "/queryTreeList")
	public Result<?> queryByParentId(@RequestParam(name="id",required=false) String id) {
		LambdaQueryWrapper<SysArea> queryWrapper = new LambdaQueryWrapper<SysArea>();
		if(oConvertUtils.isNotEmpty(id)) {//传了id，根据父节点查询子节点列表
			queryWrapper.eq(SysArea::getParentId, id);
		}else {//没传id，查询一级列表
			queryWrapper.isNull(SysArea::getParentId);
		}
		queryWrapper.eq(SysArea::getDelFlag, 0);
		List<SysArea> list = sysAreaService.list(queryWrapper);
		return Result.ok(list);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param sysArea
   */
	@GetMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, SysArea sysArea) {
		sysArea.setDelFlag(0);//只导出未删除的
		return super.exportXls(request, sysArea, SysArea.class, "区划管理");
	}

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      return super.importExcel(request, response, SysArea.class);
  }

}
